package com.ruoyi.system.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.system.domain.equipment.EquipmentBook;
import com.ruoyi.system.domain.equipment.EquipmentByzx;
import com.ruoyi.system.mapper.equipment.EquipmentBookMapper;
import com.ruoyi.system.mapper.equipment.EquipmentByzxMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: zhengxiong.jiang
 * @createDate: 2023/10/12
 * @version: 1.0
 */
@Service
public class EquipmentTaskServiceImpl implements EquipmentTaskService {

    @Autowired
    private EquipmentBookMapper equipmentBookMapper;
    @Autowired
    private EquipmentByzxMapper equipmentByzxMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Async
    public String alertTask() {
        List<EquipmentBook> equipmentBooks = equipmentBookMapper.selectList(new QueryWrapper<>());
        equipmentBooks.stream().forEach(i -> {
            Date applyDate = i.getApplyDate();
            Integer alertDays = i.getAlertDays();
            //获取设备保养预警提醒的时间
            Long yjDateTime = DateUtil.offset(applyDate, DateField.DAY_OF_MONTH, -alertDays).getTime();
            Long time = new Date().getTime();
            if (time >= yjDateTime) {
                //开始预警
                EquipmentByzx equipmentByzx = equipmentByzxMapper
                        .selectOne(new QueryWrapper<EquipmentByzx>()
                                .eq("equipment_id", i.getBookId())
                                .eq("alert_state", 0));
                if (ObjectUtil.isNotNull(equipmentByzx)) {
                    equipmentByzx.setAlertState(1);
                    equipmentByzxMapper.updateById(equipmentByzx);
                }
            }
        });
        return null;
    }
}
